package cn.wolfcode.crud.shiro;

import cn.wolfcode.crud.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/*
因为他原来的返回是一个视图,不能满足我们,所以重写他的返回方法
* */
@Component("ajaxFormAuthenticationFilter")
public class AjaxFormAuthenticationFilter extends FormAuthenticationFilter {

    //登录成功的方法,返回false表示不放行,我们自己处理返回的东西
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        //登录成功success默认为true
        JsonResult jsonResult = new JsonResult();
        //设置响应编码
        response.setContentType("application/json;charset=utf-8");
        //把java对象转换成json对象响应回去
        response.getWriter().print(JSON.toJSONString(jsonResult));
        return false;
    }


    //登录失败
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        e.printStackTrace();
        //登录成功success默认为true
        JsonResult jsonResult = new JsonResult(false,"登陆失败");
        //设置响应编码
        response.setContentType("application/json;charset=utf-8");
        //把java对象转换成json对象响应回去
        try {
            response.getWriter().print(JSON.toJSONString(jsonResult));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return false;
    }
}
